Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Google Medium
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Google Hard
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Trapping Rain Water

Problem Statement

Given an array of positive integers height, where height[i] represents the height of the bar in the elevation map and each bar has width 1, return how much water it can trap after raining.

Examples

Example 1:

  • Input: height = [4, 0, 3, 0, 2]
Image
  • Expected Output: 5
  • Justification: The first and third bars form a container that traps 3 units of water. The third and fifth bars trap an additional 2 units. Therefore, the total trapped water is 5 units.

Example 2:

  • Input: height = [1, 2, 1, 2, 1]
Image
  • Expected Output: 1
  • Justification: Water is only trapped between the second and fourth bars, holding 1 unit of water.

Example 3:

  • Input: height = [3, 1, 2, 4, 0, 1, 3]
Image
  • Expected Output: 8
  • Justification: The first, and fourth bars trap 3 units of water. The fourth, and seventh bars trap an additional 5 units. The total is 8 units of trapped water.

Constraints:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

Solution

To solve this problem, we'll employ a two-pointer technique, which is efficient for this kind of linear space problem. This approach works by iterating over the elevation map from both ends towards the center, calculating the potential water trap at each step. We believe this method is effective because it allows us to compute the maximum water trapped by considering the minimum height between two points at a time, which is the limiting factor for water trapping. This way, we can efficiently calculate the trapped water without needing to consider all possible containers formed between bars, significantly reducing the computational complexity.

The essence of our approach is to keep track of the left and right maximum heights as we move the pointers towards the center. By comparing these heights, we can determine the amount of water that can be trapped at each step based on the difference between the current height and the minimum of the two maximum heights. This strategy ensures that we only need to pass through the elevation map once, making it a highly efficient solution.

Step-by-Step Algorithm

  1. Initialize Pointers and Variables:

    • Set two pointers, left and right, to point at the start and end of the array, respectively.
    • Initialize two variables, leftMax and rightMax, to 0. These will keep track of the maximum height encountered so far from the left and right sides.
    • Initialize a variable waterTrapped to 0. This will accumulate the total amount of water trapped.
  2. Iterate Over the Array:

    • While the left pointer is less than the right pointer, do the following:
      • Compare the height at the left pointer with the height at the right pointer.
      • If the height at left is less than the height at right:
        • Update leftMax to the maximum of leftMax and the height at the current left position.
        • Calculate the water trapped at the current left position as the difference between leftMax and the height at left, and add it to waterTrapped. If the difference is negative, add 0 instead.
        • Increment the left pointer to move it towards the center.
      • Else (if the height at right is less than or equal to the height at left):
        • Update rightMax to the maximum of rightMax and the height at the current right position.
        • Calculate the water trapped at the current right position as the difference between rightMax and the height at right, and add it to waterTrapped. If the difference is negative, add 0 instead.
        • Decrement the right pointer to move it towards the center.
  3. Return the Total Water Trapped:

    • After the loop terminates (when left meets right), return the waterTrapped variable as the total amount of water trapped.

Algorithm Walkthrough

Let's consider the input: height = [3, 1, 2, 4, 0, 1, 3].

  1. Initialization:

    • left = 0, right = 6, leftMax = 0, rightMax = 0, waterTrapped = 0
  2. First Iteration:

    • left = 0, right = 6, height[left] = 3, height[right] = 3
    • Since height[left] is not less than height[right], we look to update rightMax and calculate water for right.
    • rightMax is updated to 3.
    • No water is trapped because rightMax equals height[right].
    • Decrement right.
    • waterTrapped = 0.
  3. Second Iteration:

    • left = 0, right = 5, height[left] = 3, height[right] = 1
    • height[left] is greater than height[right], so we update rightMax if needed and calculate water for right.
    • rightMax remains 3.
    • Water trapped at right = 5 is 3 - 1 = 2.
    • Decrement right.
    • waterTrapped = 2.
  4. Third Iteration:

    • left = 0, right = 4, height[left] = 3, height[right] = 0
    • rightMax remains 3.
    • Water trapped at right = 4 is 3 - 0 = 3.
    • Decrement right.
    • waterTrapped = 5.
  5. Fourth Iteration:

    • left = 0, right = 3, height[left] = 3, height[right] = 4
    • leftMax remains 3.
    • No water is trapped because leftMax equals height[left].
    • Increment left.
    • waterTrapped = 5.
  6. Fifth Iteration:

    • left = 1, right = 3, height[left] = 1, height[right] = 4
    • leftMax remains 3.
    • Water trapped at left = 1 is 3 - 1 = 2.
    • Increment left.
    • waterTrapped = 7.
  7. Sixth Iteration:

    • left = 2, right = 3, height[left] = 2, height[right] = 4
    • leftMax remains 3.
    • Water trapped at left = 2 is 3 - 2 = 1.
    • Increment left.
    • waterTrapped = 8.
  8. Seventh Iteration:

    • The loop terminates because left is no longer less than right.
  9. Conclusion:

    • The total waterTrapped is 8.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the algorithm is , where n is the number of elements in the input array. This efficiency is achieved because the algorithm makes a single pass through the array, with two pointers moving towards the center from both ends. Each element is accessed exactly once to update the trapped water calculation and the left/right max heights, ensuring linear time complexity.

Space Complexity

The space complexity of the algorithm is . This is because the algorithm uses a constant amount of extra space regardless of the input size.

Trapping Rain Water (hard)
First Missing Positive (hard)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity